import React from 'react'
import { Modal, Button, Form, Input, Select, Row, Col, InputNumber, message } from 'antd'
import {
  statusOrderChangeApply,
  contractChangeType,
  contractChangeBusinessType,
  contractOrderStatus,
  contractChangeReason,
  quoteType
} from 'utils/enumConfig'
import ContractTableModal from './ContractTableModal'
import { LwjArea }  from 'components'
import LwjUpload from 'components/LwjUpload/LwjUpload'
import { validatorCharacters } from 'utils/utils';

const FormItem = Form.Item
const Option = Select.Option

const CreateModal = ({
  onOk,
  item,
  form: {
    getFieldDecorator,
    validateFields,
    setFieldsValue,
    getFieldValue,
    resetFields
  },
  dispatch,
  contractItems,
  contractModalVisible,
  contractSelectedRowKeys,
  contractItem,
  changeType,
  ...createModalProps
}) => {
  const contractTableModalProps = {
    items: contractItems,
    dispatch,
    title: '选择合同',
    visible: contractModalVisible,
    width: 1000,
    selectedRowKeys: contractSelectedRowKeys,
    changeType: changeType,
    destroyOnClose: true,
    onOpenContract: () => {
      dispatch({
        type: 'contractOrders/querySuccess',
        payload: {
          content: [],
          number: 0,
          totalElements: 0,
        }
      })
      dispatch({
        type: 'contractOrders/clearContractSelectedRowKeys',
        payload: {}
      })
      dispatch({
        type: 'orderChangeApply/openContractModal',
        payload: {}
      })
    },
    onCancel: () => {
      dispatch({
        type: 'orderChangeApply/hideContractModal',
        payload: {}
      })
    },
    onOk: () => {
      if (contractSelectedRowKeys.length === 0) {
        message.warning('请选择一份合同')
        return
      }
      dispatch({
        type: 'contractOrders/onShow',
        payload: {
          id: contractSelectedRowKeys[0]
        }
      })
      dispatch({
        type: 'orderChangeApply/hideContractModal',
        payload: {}
      })
    },
  }

  const formItemLayout = {
    labelCol: {
      xs: { span: 8, offset: 0 },
      sm: { span: 8, offset: 0 },
    },
    wrapperCol: {
      xs: { span: 8, offset: 0 },
      sm: { span: 8, offset: 0 },
    },
  }

  const onSubmit = (e) => {
    e.preventDefault()
    validateFields((err, values) => {
      if (!err) {
        delete values.accountType
        values.contractChangeType = changeType
        onOk(values)
      }
    })
  }

  /**
   * 处理变更合同金额
   * @param value
   * @param orderAmount
   * @param changeAmount
   */
  const changeAmountFunc = (value, orderAmount, changeAmount) => {
    let changedAmount = 0
    switch (value) {
      case 'SUPPLEMENT':
        changedAmount = parseFloat(orderAmount) + parseFloat(changeAmount)
        setFieldsValue({
          'changedAmount': changedAmount
        })
        break
      case 'REFUND':
        changedAmount = parseFloat(orderAmount) - parseFloat(changeAmount)
        if (changedAmount > 0) {
          setFieldsValue({
            'changedAmount': changedAmount
          })
        } else {
          Modal.warning({
            title: '错误',
            content: '退款时变更金额必须小于原合同金额'
          })
          resetFields(['changeAmount', 'changedAmount'])
          break
        }
    }
  }

  const modalOpts = {
    ...createModalProps,
    onOk: onSubmit,
  }

  const xlsProps = {
    maxfile: 1,
    target: '/services/upload/order',
    accept: '.xlsx,.xls,.zip,.rar',
    uploadIcon: 'upload',
    fileType: '',
    onChange(value) {
    },
    showUploadList: true
  }

  /**
   * 变更类型的Option拼装
   * @returns {Array}
   */
  const optionBuilder = (type) => {
    let option = []
    Object.keys(type).forEach((key) => { option.push(<Option key={key} value={key}>{type[key]}</Option>) })

    return option
  }

  /** @namespace item.contractChangeType */
  /** @namespace item.contractChangeBusinessType */
  /** @namespace contractItem.consigneeAddress */
  /** @namespace contractItem.endOrderAttachment */
  return (
    <Modal {...modalOpts}>
      <Form layout="horizontal">
        <Row>
          <Col span={12}>
            <FormItem {...formItemLayout} hasFeedback label="选择合同">
              <Button
                icon="plus"
                type="primary"
                onClick={contractTableModalProps.onOpenContract}>
              </Button>
            </FormItem>

            {contractItem.id && <FormItem {...formItemLayout} label="合同号">
              {contractItem.id && contractItem.contractNum}
            </FormItem>}

            {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
              <FormItem {...formItemLayout} hasFeedback label="变更业务类型">
                {getFieldDecorator('contractChangeBusinessType', {
                  rules: [{ required: true, message: '变更业务类型必须选择!' }],
                  initialValue: 'SUPPLEMENT'
                })(<Select onChange={(value) => {
                  const orderAmount = getFieldValue('orderAmount')
                  const changeAmount = getFieldValue('changeAmount') || 0

                  changeAmountFunc(value, orderAmount, changeAmount)

                }}>
                  {optionBuilder(contractChangeBusinessType)}
                </Select>)}
              </FormItem>}


            {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
              <FormItem {...formItemLayout} hasFeedback label="原合同总金额">
                {getFieldDecorator('preOrderAmount', {
                  rules: [{ required: true, message: '原合同总金额必须填写!' }],
                  initialValue: contractItem.orderQuoteSummary ? contractItem.orderQuoteSummary.preOrderAmount : ''
                })(<Input disabled={true} />)}
              </FormItem>}

            {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
              <FormItem {...formItemLayout} hasFeedback label="装修返点金额">
                {getFieldDecorator('decorationRebateAmount', {
                  rules: [{ required: true, message: '装修返点金额必须填写!' }],
                  initialValue: contractItem.orderQuoteSummary ? contractItem.orderQuoteSummary.decorationRebateAmount : ''
                })(<Input disabled={true} />)}
              </FormItem>}

            {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
              <FormItem {...formItemLayout} hasFeedback label="样柜返点金额">
                {getFieldDecorator('cabinetRebateAmount', {
                  rules: [{ required: true, message: '样柜返点金额必须填写!' }],
                  initialValue: contractItem.orderQuoteSummary ? contractItem.orderQuoteSummary.cabinetRebateAmount : ''
                })(<Input disabled={true} />)}
              </FormItem>}

            {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
              <FormItem {...formItemLayout} hasFeedback label="活动优惠金额">
                {getFieldDecorator('eventsAmount', {
                  rules: [{ required: true, message: '活动优惠金额必须填写!' }],
                  initialValue: contractItem.orderQuoteSummary ? contractItem.orderQuoteSummary.eventsAmount : ''
                })(<Input disabled={true} />)}
              </FormItem>}

            {contractItem.id && changeType === 'INFORMATION' && <FormItem {...formItemLayout} hasFeedback label="收货人">
              {getFieldDecorator('consigneeName', {
                rules: [
                  {
                    required: true,
                    message: '客户姓名不能为空',
                    whitespace: true
                  },
                  {
                    max: 5,
                    message: '客户姓名长度不能大于5',
                    whitespace: true
                  }
                  , {
                    validator: validatorCharacters
                  }
                ],
                initialValue: contractItem ? contractItem.consigneeName : ''
              })(<Input />)}
            </FormItem>}

            {contractItem.id && changeType === 'INFORMATION' && <FormItem {...formItemLayout} hasFeedback label="收货人电话">
              {getFieldDecorator('consigneePhoneNum', {
                rules: [{ required: true, message: '收货人必须填写!' }],
                initialValue: contractItem ? contractItem.consigneePhoneNum : ''
              })(<Input />)}
            </FormItem>}

            {contractItem.id && changeType === 'INFORMATION' && !_.isEmpty(contractItem.consigneeRegion) &&
              <FormItem {...formItemLayout} label="收货人地址">
                {getFieldDecorator('consigneeRegion', {
                  rules: [
                    {
                      required: true,
                      message: '请选择收货人地址',
                      type: 'array'
                    }
                  ],
                  initialValue: contractItem ? contractItem.consigneeRegion : []
                })(<LwjArea width={'100%'} />)}
              </FormItem>}

            {contractItem.id && changeType === 'INFORMATION' &&
              <FormItem {...formItemLayout} hasFeedback label="收货人详细地址">
                {getFieldDecorator('address', {
                  rules: [{ required: true, message: '收货人详细地址必须填写!' }],
                  initialValue: contractItem ? contractItem.consigneeAddress : ''
                })(<Input />)}
              </FormItem>}
          </Col>

          <Col span={12}>
            {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
              <FormItem {...formItemLayout} hasFeedback label="原合同金额">
                {getFieldDecorator('orderAmount', {
                  rules: [{ required: true, message: '原合同金额必须填写!' }],
                  initialValue: contractItem.orderQuoteSummary ? contractItem.orderQuoteSummary.orderAmount : ''
                })(<Input disabled={true} />)}
              </FormItem>}

            {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
              <FormItem {...formItemLayout} hasFeedback label="变更金额">
                {getFieldDecorator('changeAmount', {
                  validateTrigger: ['onBlur', 'onSubmit'],
                  rules: [{ required: true, message: '变更金额必须填写!' }, {
                    validator: (rule, value, callback) => {
                      const orderAmount = getFieldValue('orderAmount')
                      const changeAmount = value || 0
                      if (isNaN(value) || value <= 0) {
                        callback('请输入大于0的数字')

                        return
                      }

                      // 判断是补款还是退款
                      let contractChangeBusinessType = getFieldValue('contractChangeBusinessType')
                      if (typeof contractChangeBusinessType === 'undefined') {
                        Modal.warning({
                          title: '提示',
                          content: '变更业务类型未选择'
                        })
                        resetFields(['changeAmount'])
                        return
                      }

                      changeAmountFunc(contractChangeBusinessType, orderAmount, changeAmount)
                      callback()
                    }
                  }],
                  initialValue: 0
                })(<InputNumber />)}
              </FormItem>}
            {contractItem.id && changeType === 'AMOUNT' && <FormItem {...formItemLayout} hasFeedback label="支付方式">
              {getFieldDecorator('accountType', {
                rules: [{ required: true, message: '支付方式必须天蝎' }],
                initialValue: contractItem.orderQuoteSummary ? contractItem.orderQuoteSummary.deductionType : ''
              })(<Select disabled={true}>
                 <Option key={contractItem.orderQuoteSummary.deductionType}>{quoteType[contractItem.orderQuoteSummary.deductionType]}</Option>
              </Select>)}
            </FormItem>}
            {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
              <FormItem {...formItemLayout} hasFeedback label="变更后合同金额">
                {getFieldDecorator('changedAmount', {
                  rules: [{ required: true, message: '变更后合同金额必须填写!' }],
                  initialValue: contractItem.orderQuoteSummary ? contractItem.orderQuoteSummary.orderAmount : ''
                })(<Input disabled={true} />)}
              </FormItem>}


            {contractItem.id && changeType === 'AMOUNT' && <FormItem {...formItemLayout} hasFeedback label="变更原因">
              {getFieldDecorator('contractChangeReason', {
                rules: [{ required: true, message: '变更业务类型必须选择!' }],
              })(<Select>
                {optionBuilder(contractChangeReason)}
              </Select>)}
            </FormItem>}

            {contractItem.id && changeType === 'AMOUNT' && typeof contractItem.orderQuoteSummary !== 'undefined' &&
              <FormItem {...formItemLayout} label="报价方案">
                {getFieldDecorator('quoteAttachment', {
                  rules: [{ required: true, message: '报价方案必须上传!' }],
                  initialValue: contractItem.orderQuoteSummary ? contractItem.orderQuoteSummary.quoteAttachment : ''
                })(<LwjUpload {...xlsProps}
                  fileLists={contractItem.orderQuoteSummary ? contractItem.orderQuoteSummary.quoteAttachment : ''} />)}
              </FormItem>}

            {contractItem.id && changeType === 'INFORMATION' && contractItem.productType !== 'END' &&
              <FormItem {...formItemLayout} label="设计方案">
                {getFieldDecorator('designAttachment', {
                  rules: [{ required: true, message: '设计方案必须上传!' }],
                  initialValue: contractItem.designAttachment || ''
                })(<LwjUpload {...xlsProps} fileLists={contractItem.designAttachment || ''} />)}
              </FormItem>}

            {contractItem.id && changeType === 'INFORMATION' && contractItem.productType === 'END' &&
              <FormItem {...formItemLayout} label="成品清单">
                {getFieldDecorator('endOrderAttachment', {
                  rules: [{ required: true, message: '成品清单必须上传!' }],
                  initialValue: contractItem.endOrderAttachment || ''
                })(<LwjUpload {...xlsProps} fileLists={contractItem.endOrderAttachment || ''} />)}
              </FormItem>}

            {contractItem.id && <FormItem {...formItemLayout} hasFeedback label="备注">
              {getFieldDecorator('des', {
                rules: [],
              })(<Input />)}
            </FormItem>}
          </Col>
        </Row>
      </Form>
      {contractModalVisible && <ContractTableModal {...contractTableModalProps} />}
    </Modal>
  )
}

export default Form.create()(CreateModal)
